package com.ruanda.spongebobrunner.game;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.ruanda.spongebobrunner.R;
import com.ruanda.spongebobrunner.ui.GameButton;
import com.ruanda.spongebobrunner.ui.PowerUp;
import com.ruanda.spongebobrunner.utils.SoundUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

// 导入新创建的封装类

public class GameView extends SurfaceView implements SurfaceHolder.Callback {
    // 游戏状态常量
    private static final int START_SCREEN = 0;
    private static final int IN_GAME = 1;
    private static final int TRANSITION = 2;
    private static final int GAME_OVER = 3;
    private static final int SETTINGS_SCREEN = 4; // 新增设置界面状态

    // 游戏状态
    private int gameState = START_SCREEN;

    // 游戏线程
    private GameThread gameThread;

    // 绘图相关
    private Paint paint;
    private Paint textPaint;

    // 资源相关
    private Bitmap bgImage1;
    private Bitmap bgImage2;
    private Bitmap[] spongeAnim;
    private Bitmap groundImage;
    private Bitmap obstacleImage;
    private MediaPlayer bgmMain;
    private MediaPlayer bgmGame;

    // 玩家相关
    private Player player;
    private int playerX;
    private int playerSpeed = 25;
    private int jumpPower = -20;
    private float gravity = 0.8f;
    private float velocityY = 0;
    private boolean isJumping = false;
    private boolean doubleJumpAvailable = false;
    private int animIndex = 0;
    private long animTimer = 0;
    private Bitmap deathAnimationBitmap = null; // 用于死亡动画的缓存Bitmap

    // 地形和障碍物系统
    private List<Rect> groundTiles;
    private List<Rect> obstacles;
    private int scrollSpeed = 10; // 增加滚动速度，使游戏更快
    private int spawnTimer = 0;
    private int tileWidth = 200; // 地面瓷砖宽度增大一倍
    private int tileHeight = 100; // 地面瓷砖高度增大一倍
    private int lastObstacleX = 0; // 记录上一个障碍物的位置
    private Random random;

    // 游戏数据
    private int score = 0;
    private long startTime;
    private boolean paused = false;

    // 音量控制变量
    private float bgmMainVolume = 0.5f; // 主界面BGM音量 (0.0 - 1.0)
    private float bgmGameVolume = 0.5f; // 游戏内BGM音量 (0.0 - 1.0)
    private boolean isBgmMainMuted = false; // 主界面BGM是否静音
    private boolean isBgmGameMuted = false; // 游戏内BGM是否静音

    // 设置界面滚动相关变量
    private float settingsScrollY = 0; // 设置界面垂直滚动偏移
    private float lastTouchY = 0; // 上一次触摸点的Y坐标
    private boolean isScrolling = false; // 是否正在滚动

    // 难度设置相关
    private int difficulty = 0; // 0: 简单, 1: 困难
    private int initialScrollSpeed = 5; // 初始滚动速度
    private int savedScrollSpeed = 5; // 保存的滚动速度
    private int maxScrollSpeed = 30; // 最大滚动速度
    private int obstacleIncreaseRate = 0; // 障碍物增加率
    private boolean reverseScrolling = false; // 是否反向滚动

    // 按钮区域
    private GameButton startButton; // 开始游戏按钮
    private GameButton exitButton; // 退出游戏按钮
    private GameButton settingsButton; // 暂停按钮
    private GameButton continueButton; // 继续游戏按钮
    private GameButton pauseMainButton; // 暂停主菜单按钮
    private GameButton pauseExitButton; // 暂停退出按钮
    private GameButton restartButton; // 重新开始按钮
    private GameButton dieMainButton; // 死亡主菜单按钮
    private GameButton dieExitButton; // 暂停退出按钮

    // 设置界面按钮
    private GameButton settingsIcon; // 右上角设置图标
    private GameButton easyButton; // 简单难度按钮
    private GameButton hardButton; // 困难难度按钮
    private GameButton confirmButton; // 确认按钮
    private GameButton settingsExitButton; // 设置界面退出按钮
    private GameButton minusButton; // 减号按钮
    private GameButton plusButton; // 加号按钮

    // 音量控制相关按钮
    private GameButton bgmMainMinusButton; // 主界面BGM音量减按钮
    private GameButton bgmMainPlusButton; // 主界面BGM音量加按钮
    private GameButton bgmMainMuteButton; // 主界面BGM静音按钮
    private GameButton bgmGameMinusButton; // 游戏内BGM音量减按钮
    private GameButton bgmGamePlusButton; // 游戏内BGM音量加按钮
    private GameButton bgmGameMuteButton; // 游戏内BGM静音按钮

    // 死亡动画相关变量
    private boolean isDying = false;
    private long deathStartTime = 0;
    private static final long DEATH_ANIMATION_DURATION = 2000; // 2秒死亡动画，给人物足够时间掉出屏幕
    private float deathVelocityY = -20; // 向上的初始速度，与跳跃相同
    private static final float DEATH_GRAVITY = 0.8f; // 死亡动画重力，与正常游戏相同

    // 音效工具类
    private SoundUtils soundUtils = new SoundUtils(getContext());

    // 生命值相关变量
    private int currentLives = 3; // 当前生命值
    private int maxLives = 3; // 最大生命值
    private Bitmap lifeImage; // 有生命时显示的图像
    private Bitmap notLifeImage; // 无生命时显示的图像

    // 无敌时间相关变量
    private boolean isInvincible = false; // 是否处于无敌状态
    private long invincibleStartTime = 0; // 无敌开始时间
    private static final long INVINCIBLE_DURATION = 3000; // 无敌持续时间(毫秒)

    // 道具系统相关变量
    private List<PowerUp> powerUps;
    private Bitmap lifePowerUpImage; // 生命道具图像
    private static final float LIFE_POWER_UP_SPAWN_PROBABILITY = 0.3f; // 生命道具出现概率
    private long lastPowerUpTime = 0; // 上一次生成道具的时间
    private int lastPowerUpX = 0; // 上一次生成道具的位置
    private int powerUpsThisMinute = 0; // 当前分钟生成的道具数量
    private long lastMinuteCheck = 0; // 上一次检查分钟的时间

    public GameView(Context context) {
        super(context);
        getHolder().addCallback(this);

        // 设置全屏和沉浸式模式
        setSystemUiVisibility(
                SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION | SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

        // 初始化绘图对象
        paint = new Paint();
        textPaint = new Paint();
        textPaint.setTextSize(60);
        textPaint.setColor(Color.WHITE);
        textPaint.setAntiAlias(true);

        // 加载自定义字体
        try {
            Typeface customFont = Typeface.createFromAsset(context.getAssets(), "fonts/YeZiGongChangZhaoPaiTi-2.ttf");
            textPaint.setTypeface(customFont);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 加载保存的设置
        loadSettings();

        // 初始化资源
        initResources();

        // 初始化玩家，增大尺寸
        player = new Player();
        player.init(playerX, getHeight() - 260, 160, 160, getHeight() - 100);

        // 初始化地形和障碍物系统
        groundTiles = new ArrayList<>();
        obstacles = new ArrayList<>();
        powerUps = new ArrayList<>(); // 初始化道具列表
        random = new Random();

        // 初始化按钮
        initButtons();

        // 开始播放主菜单音乐
        if (bgmMain != null) {
            bgmMain.setLooping(true);
            bgmMain.start();
        }
    }

    /**
     * 保存用户设置到SharedPreferences
     */
    private void saveSettings() {
        SharedPreferences prefs = getContext().getSharedPreferences("game_settings", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("difficulty", difficulty);
        editor.putInt("savedScrollSpeed", savedScrollSpeed);
        editor.putFloat("bgmMainVolume", bgmMainVolume);
        editor.putFloat("bgmGameVolume", bgmGameVolume);
        editor.putBoolean("isBgmMainMuted", isBgmMainMuted);
        editor.putBoolean("isBgmGameMuted", isBgmGameMuted);
        editor.apply();
    }

    /**
     * 从SharedPreferences加载用户设置
     */
    private void loadSettings() {
        SharedPreferences prefs = getContext().getSharedPreferences("game_settings", Context.MODE_PRIVATE);
        difficulty = prefs.getInt("difficulty", 0); // 默认简单模式
        savedScrollSpeed = prefs.getInt("savedScrollSpeed", 5); // 默认滚动速度5
        bgmMainVolume = prefs.getFloat("bgmMainVolume", 0.5f); // 默认主界面BGM音量
        bgmGameVolume = prefs.getFloat("bgmGameVolume", 0.5f); // 默认游戏内BGM音量
        isBgmMainMuted = prefs.getBoolean("isBgmMainMuted", false); // 默认不静音
        isBgmGameMuted = prefs.getBoolean("isBgmGameMuted", false); // 默认不静音

        initialScrollSpeed = savedScrollSpeed;
    }


    /**
     * 初始化游戏资源
     */
    private void initResources() {
        try {
            // 加载背景图片
            bgImage1 = BitmapFactory.decodeResource(getResources(), R.drawable.hm_bg_1);
            bgImage2 = BitmapFactory.decodeResource(getResources(), R.drawable.hm_bg_2);

            // 加载玩家动画帧
            spongeAnim = new Bitmap[4];
            spongeAnim[0] = BitmapFactory.decodeResource(getResources(), R.drawable.hm_right_1);
            spongeAnim[1] = BitmapFactory.decodeResource(getResources(), R.drawable.hm_right_2);
            spongeAnim[2] = BitmapFactory.decodeResource(getResources(), R.drawable.hm_right_3);
            spongeAnim[3] = BitmapFactory.decodeResource(getResources(), R.drawable.hm_right_4);

            // 加载地形和障碍物图片
            groundImage = BitmapFactory.decodeResource(getResources(), R.drawable.ground11);
            obstacleImage = BitmapFactory.decodeResource(getResources(), R.drawable.spike);

            // 加载音频资源
            bgmMain = MediaPlayer.create(getContext(), R.raw.bgm_main);
            bgmGame = MediaPlayer.create(getContext(), R.raw.bgm_game);

            // 加载生命值图像资源
            lifeImage = BitmapFactory.decodeResource(getResources(), R.drawable.life);
            notLifeImage = BitmapFactory.decodeResource(getResources(), R.drawable.not_life);

            // 加载道具图像资源
            lifePowerUpImage = BitmapFactory.decodeResource(getResources(), R.drawable.life);

            // 使用保存的音量设置
            if (bgmMain != null) {
                float volume = isBgmMainMuted ? 0.0f : bgmMainVolume;
                bgmMain.setVolume(volume, volume);
            }
            if (bgmGame != null) {
                float volume = isBgmGameMuted ? 0.0f : bgmGameVolume;
                bgmGame.setVolume(volume, volume);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            // 处理内存不足错误
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (gameThread == null || !gameThread.isAlive()) {
            gameThread = new GameThread(getHolder());
            gameThread.setRunning(true);
            gameThread.start();
        }
    }

    /**
     * 初始化按钮
     **/
    private void initButtons() {
        // 初始化居中按钮，调整按钮大小
        int buttonWidth = 400; // 增大按钮宽度
        int buttonHeight = 100; // 增大按钮高度
        int buttonSpacing = 60; // 增大按钮间距
        int pauseButtonSpacing = 40; // 增大按钮间距
        int startY = getHeight() / 2 - 150; // 调整按钮起始Y坐标

        startButton = new GameButton(getContext(),
                new Rect(
                        (getWidth() - buttonWidth) / 2,
                        startY,
                        (getWidth() + buttonWidth) / 2,
                        startY + buttonHeight),
                "开始游戏",
                0xFF4CAF50, 0xFF388E3C,
                0xFFFFFFFF, 18, 20);

        exitButton = new GameButton(getContext(),
                new Rect(
                        (getWidth() - buttonWidth) / 2,
                        startY + buttonHeight + buttonSpacing,
                        (getWidth() + buttonWidth) / 2,
                        startY + buttonHeight * 2 + buttonSpacing),
                "退出游戏",
                0xFFF44336, 0xFFD32F2F,
                0xFFFFFFFF, 18, 20);

        settingsButton = new GameButton(getContext(),
                new Rect(getWidth() - 160, 40, getWidth() - 80, 120),
                "",
                0xFF2196F3, 0xFF1976D2,
                0xFFFFFFFF, 18, 30);

        settingsIcon = new GameButton(getContext(),
                new Rect(getWidth() - 160, 40, getWidth() - 80, 120),
                "",
                -14575885, -7287815,
                0xFF757575, 24, 20);

        continueButton = new GameButton(getContext(),
                new Rect(
                        (getWidth() - buttonWidth) / 2,
                        getHeight() / 2 - buttonHeight - pauseButtonSpacing,
                        (getWidth() + buttonWidth) / 2,
                        getHeight() / 2 - pauseButtonSpacing),
                "继续游戏",
                -11751600, -8206459,
                0xFFFFFFFF, 14, 20);

        pauseMainButton = new GameButton(getContext(), new Rect(
                (getWidth() - buttonWidth) / 2,
                getHeight() / 2,
                (getWidth() + buttonWidth) / 2,
                getHeight() / 2 + buttonHeight),
                "返回主界面",
                -26624, -21197,
                0xFFFFFFFF, 14, 20);

        pauseExitButton = new GameButton(getContext(),
                new Rect(
                        (getWidth() - buttonWidth) / 2,
                        getHeight() / 2 + buttonHeight + pauseButtonSpacing,
                        (getWidth() + buttonWidth) / 2,
                        getHeight() / 2 + buttonHeight * 2 + pauseButtonSpacing),
                "退出游戏",
                -769226, -628386,
                0xFFFFFFFF, 14, 20);

        // 初始化音量控制按钮（在设置界面中使用）
        int menuWidth = getWidth() / 2;
        int menuLeft = (getWidth() - menuWidth) / 2;
        // 统一设置选项的高度和间距
        int optionHeight = 120; // 每个设置选项的高度
        int labelContentSpacing = 30; // label与内容的间距
        int optionSpacing = 50; // 选项之间的间距
        // 计算菜单总高度
        int titleHeight = 80; // 标题高度
        int titleSpacing = 100; // 标题与第一个选项的间距
        // 计算所有设置选项的高度
        int totalOptionsHeight = titleHeight + (optionHeight + optionSpacing) * 5;
        int menuHeight = Math.min(titleHeight + titleSpacing + totalOptionsHeight, getHeight() - 100); // 限制高度不超过屏幕高度并保留底部空间
        int menuTop = (getHeight() - menuHeight) / 2;
        // 初始化设置按钮区域
        int settingButtonWidth = menuWidth - 80;
        int buttonLeft = menuLeft + 40;
        int currentTop = menuTop + titleHeight + titleSpacing; // 当前绘制位置的顶部
        // 绘制难度切换按钮
        int toggleWidth = settingButtonWidth;
        int toggleHeight = optionHeight;
        int toggleLeft = buttonLeft;
        int toggleTop = currentTop;
        easyButton = new GameButton(getContext(),
                new Rect(toggleLeft, toggleTop - (int) settingsScrollY, toggleLeft + toggleWidth / 2,
                        toggleTop + toggleHeight - (int) settingsScrollY));
        hardButton = new GameButton(getContext(),
                new Rect(toggleLeft + toggleWidth / 2, toggleTop - (int) settingsScrollY, toggleLeft + toggleWidth,
                        toggleTop + toggleHeight - (int) settingsScrollY));
        // 更新当前绘制位置
        currentTop += toggleHeight + optionSpacing + titleHeight;
        int buttonSize = 50;
        // 绘制减号按钮
        int minusLeft = buttonLeft;
        // 绘制加号按钮
        int plusLeft = buttonLeft + buttonWidth - buttonSize;
        int muteLeft = plusLeft - buttonSize - 10;
        minusButton = new GameButton(getContext(),
                new Rect(minusLeft, currentTop - (int) settingsScrollY, minusLeft + buttonSize,
                        currentTop + buttonSize - (int) settingsScrollY),
                "-", 0xFF808080, 0xFF606060, 
                0xFFFFFFFF, 12, 8);
        plusButton = new GameButton(getContext(),
                new Rect(plusLeft, currentTop - (int) settingsScrollY, plusLeft + buttonSize,
                        currentTop + buttonSize - (int) settingsScrollY),
                "+", 0xFF808080, 0xFF606060,
                0xFFFFFFFF, 12, 8);
        // 更新当前绘制位置
        currentTop += optionHeight + optionSpacing;
        bgmMainMinusButton = new GameButton(getContext(),
                new Rect(minusLeft, currentTop - (int) settingsScrollY,
                        currentTop + buttonSize,
                        minusLeft + buttonSize - (int) settingsScrollY),
                "-", 0xFF808080, 0xFF606060,
                0xFFFFFFFF, 12, 8);
        bgmMainPlusButton = new GameButton(getContext(),
                new Rect(plusLeft, currentTop - (int) settingsScrollY,
                        plusLeft + buttonSize,
                        currentTop + buttonSize - (int) settingsScrollY),
                "+", 0xFF808080, 0xFF606060,
                0xFFFFFFFF, 12, 8);
        bgmMainMuteButton = new GameButton(getContext(),
                new Rect(muteLeft, currentTop - (int) settingsScrollY,
                        currentTop + buttonSize,
                        muteLeft + buttonSize - (int) settingsScrollY));
        // 更新当前绘制位置
        currentTop += optionHeight + optionSpacing;
        bgmGameMinusButton = new GameButton(getContext(),
                new Rect(buttonLeft, currentTop - (int) settingsScrollY,
                        buttonLeft + buttonSize,
                        currentTop + buttonSize - (int) settingsScrollY),
                "-", 0xFF808080, 0xFF606060,
                0xFFFFFFFF, 12, 8);
        bgmGamePlusButton = new GameButton(getContext(),
                new Rect(plusLeft, currentTop - (int) settingsScrollY,
                        plusLeft + buttonSize,
                        currentTop + buttonSize - (int) settingsScrollY),
                "+", 0xFF808080, 0xFF606060,
                0xFFFFFFFF, 12, 8);
        bgmGameMuteButton = new GameButton(getContext(),
                new Rect(muteLeft, currentTop - (int) settingsScrollY,
                        currentTop + buttonSize,
                        muteLeft + buttonSize - (int) settingsScrollY));
        // 更新当前绘制位置
        currentTop += optionHeight + optionSpacing;
        confirmButton = new GameButton(getContext(), new Rect(buttonLeft, currentTop - (int) settingsScrollY,
                buttonLeft + buttonWidth, currentTop + optionHeight - (int) settingsScrollY),
                "确认保存",-14575885, -7287815,
                0xFFFFFFFF, 18, 20);
        settingsExitButton = new GameButton(getContext(),
                new Rect(menuLeft + menuWidth - 80, menuTop + 20 - (int) settingsScrollY, menuLeft + menuWidth - 20,
                        menuTop + 80 - (int) settingsScrollY),
                "✘",-769226, -628386,
                0xFFFFFFFF, 12, 20);

        // 定义按钮位置，按顺序：重新开始、返回主界面、退出
        restartButton = new GameButton(getContext(),
                new Rect(
                        (getWidth() - buttonWidth) / 2,
                        getHeight() / 2 - buttonHeight - buttonSpacing,
                        (getWidth() + buttonWidth) / 2,
                        getHeight() / 2 - buttonSpacing),
                "重新开始",
                0xFFFFC107, 0xFFFFA000,
                0xFFFFFFFF, 18, 20);

        dieMainButton = new GameButton(getContext(),
                new Rect(
                        (getWidth() - buttonWidth) / 2,
                        getHeight() / 2,
                        (getWidth() + buttonWidth) / 2,
                        getHeight() / 2 + buttonHeight),
                "主菜单",
                0xFF2196F3, 0xFF1976D2,
                0xFFFFFFFF, 18, 20);

        dieExitButton = new GameButton(getContext(),
                new Rect(
                        (getWidth() - buttonWidth) / 2,
                        getHeight() / 2 + buttonHeight + buttonSpacing,
                        (getWidth() + buttonWidth) / 2,
                        getHeight() / 2 + buttonHeight * 2 + buttonSpacing),
                "退出游戏",
                0xFFF44336, 0xFFD32F2F,
                0xFFFFFFFF, 18, 20);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        initButtons(); // 调用统一初始化方法
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (gameThread != null) {
            boolean retry = true;
            while (retry) {
                try {
                    gameThread.setRunning(false);
                    gameThread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                    retry = false;
                }
                retry = false;
            }
        }

        // 释放音频资源
        if (bgmMain != null) {
            try {
                bgmMain.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
            bgmMain = null;
        }
        if (bgmGame != null) {
            try {
                bgmGame.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
            bgmGame = null;
        }

        // 释放死亡动画Bitmap
        if (deathAnimationBitmap != null && !deathAnimationBitmap.isRecycled()) {
            deathAnimationBitmap.recycle();
        }
        deathAnimationBitmap = null;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 重新设置全屏和沉浸式模式
        setSystemUiVisibility(
                SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION | SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

        // 添加防错处理
        if (event == null)
            return false;

        // 只处理ACTION_DOWN事件，避免重复处理
        // if (event.getAction() != MotionEvent.ACTION_DOWN) {
        //     return true;
        // }

        try {
            float x = event.getX();
            float y = event.getY();

            switch (gameState) {
                case START_SCREEN:
                    if (startButton.handleTouchEvent(event)) {
                        // 停止主菜单音乐，开始过渡动画
                        if (bgmMain != null && bgmMain.isPlaying()) {
                            bgmMain.stop();
                        }
                        gameState = TRANSITION;
                    } else if (exitButton.handleTouchEvent(event)) {
                        ((android.app.Activity) getContext()).finish();
                    } else if (settingsIcon.handleTouchEvent(event)) {
                        // 进入设置界面
                        loadSettings();
                        gameState = SETTINGS_SCREEN;
                    }
                    break;
                case TRANSITION:
                    // 过渡状态下不处理触摸事件
                    break;
                case SETTINGS_SCREEN:
                    // 处理设置界面的触摸事件
                    if (easyButton != null && easyButton.handleTouchEvent(event)) {
                        // 选择简单难度
                        difficulty = 0;
                        initialScrollSpeed = 5;
                    } else if (hardButton != null && hardButton.handleTouchEvent(event)) {
                        // 选择困难难度
                        difficulty = 1;
                        initialScrollSpeed = 10; // 困难模式最高速度也设置为20
                    } else if (confirmButton != null && confirmButton.handleTouchEvent(event)) {
                        // 确认设置，保存设置并返回主菜单
                        scrollSpeed = initialScrollSpeed;
                        savedScrollSpeed = scrollSpeed; // 保存当前滚动速度
                        saveSettings(); // 保存设置到SharedPreferences
                        gameState = START_SCREEN;
                    } else if (settingsExitButton != null
                            && settingsExitButton.handleTouchEvent(event)) {
                        // 退出设置界面，返回主菜单
                        gameState = START_SCREEN;
                    } else if (minusButton != null && minusButton.handleTouchEvent(event)) {
                        // 减少滚动速度
                        int minSpeed = (difficulty == 0) ? 5 : 10;
                        initialScrollSpeed = Math.max(minSpeed, initialScrollSpeed - 1);
                    } else if (plusButton != null && plusButton.handleTouchEvent(event)) {
                        // 增加滚动速度
                        int maxSpeed = 20; // 简单和困难模式最高速度均为20
                        initialScrollSpeed = Math.min(maxSpeed, initialScrollSpeed + 1);
                    }
                    // 处理主界面BGM音量设置按钮
                    else if (bgmMainMinusButton != null && bgmMainMinusButton.handleTouchEvent(event)) {
                        bgmMainVolume = Math.max(0.0f, bgmMainVolume - 0.1f);
                        isBgmMainMuted = false; // 取消静音
                        if (bgmMain != null) {
                            bgmMain.setVolume(bgmMainVolume, bgmMainVolume);
                        }
                    } else if (bgmMainPlusButton != null && bgmMainPlusButton.handleTouchEvent(event)) {
                        bgmMainVolume = Math.min(1.0f, bgmMainVolume + 0.1f);
                        isBgmMainMuted = false; // 取消静音
                        if (bgmMain != null) {
                            bgmMain.setVolume(bgmMainVolume, bgmMainVolume);
                        }
                    } else if (bgmMainMuteButton != null && bgmMainMuteButton.handleTouchEvent(event)) {
                        isBgmMainMuted = !isBgmMainMuted;
                        if (bgmMain != null) {
                            if (isBgmMainMuted) {
                                bgmMain.setVolume(0, 0);
                            } else {
                                bgmMain.setVolume(bgmMainVolume, bgmMainVolume);
                            }
                        }
                    }
                    // 处理游戏内BGM音量设置按钮
                    else if (bgmGameMinusButton != null && bgmGameMinusButton.handleTouchEvent(event)) {
                        bgmGameVolume = Math.max(0.0f, bgmGameVolume - 0.1f);
                        isBgmGameMuted = false; // 取消静音
                    } else if (bgmGamePlusButton != null && bgmGamePlusButton.handleTouchEvent(event)) {
                        bgmGameVolume = Math.min(1.0f, bgmGameVolume + 0.1f);
                        isBgmGameMuted = false; // 取消静音
                    } else if (bgmGameMuteButton != null && bgmGameMuteButton.handleTouchEvent(event)) {
                        isBgmGameMuted = !isBgmGameMuted;
                    }
                    break;
                case IN_GAME:
                    // 在死亡动画播放期间禁用触摸事件
                    if (isDying) {
                        // 不处理任何触摸事件
                        break;
                    }
                    if (settingsButton != null && settingsButton.handleTouchEvent(event)) {
                        paused = !paused;
                    } else if (paused) {
                        if (continueButton.handleTouchEvent(event)) {
                            paused = false;
                        } else if (pauseMainButton.handleTouchEvent(event)) {
                            // 停止游戏音乐
                            if (bgmGame != null && bgmGame.isPlaying()) {
                                bgmGame.stop();
                                try {
                                    bgmGame.prepare();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            resetGame();
                            gameState = START_SCREEN;
                            paused = false;
                            // 播放主菜单音乐
                            playMainMenuMusic();
                        } else if (pauseExitButton.handleTouchEvent(event)) {
                            ((android.app.Activity) getContext()).finish();
                        }
                    } else {
                        if (settingsButton.contains(event) || event.getAction() != MotionEvent.ACTION_DOWN) {
                            break;
                        }
                        // 触发跳跃
                        if (!isJumping) {
                            isJumping = true;
                            velocityY = jumpPower;
                            doubleJumpAvailable = true;
                            // 播放跳跃音效
                            soundUtils.playSoundJump();
                        } else if (doubleJumpAvailable) {
                            velocityY = jumpPower * 0.8f;
                            doubleJumpAvailable = false;
                            // 播放跳跃音效
                            soundUtils.playSoundJump();
                        }
                    }
                    break;
                case GAME_OVER:
                    if (restartButton.handleTouchEvent(event)) {
                        // 重置游戏数据
                        resetGame();
                        gameState = TRANSITION;
                    } else if (dieMainButton.handleTouchEvent(event)) {
                        resetGame();
                        gameState = START_SCREEN;
                        playMainMenuMusic();
                    } else if (dieExitButton.handleTouchEvent(event)) {
                        ((android.app.Activity) getContext()).finish();
                    }
                    break;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onTouchEvent(event);
    }

    private void resetGame() {
        try {
            // 重置所有游戏数据
            score = 0;
            startTime = System.currentTimeMillis();
            currentLives = maxLives; // 重置生命值

            // 重置玩家，增大尺寸
            int groundLevel = getHeight() - 100; // 地面高度
            if (player != null) {
                player.setPosition(playerX, groundLevel - 160);
                player.setGroundLevel(groundLevel);
            } else {
                player = new Player();
                player.init(playerX, groundLevel - 160, 160, 160, groundLevel);
            }
            velocityY = 0;
            isJumping = false;
            doubleJumpAvailable = false;

            // 重置地形和障碍物
            if (groundTiles != null) {
                groundTiles.clear();
            }
            if (obstacles != null) {
                obstacles.clear();
            }

            // 清空道具列表
            if (powerUps != null) {
                powerUps.clear();
            }

            // 重置道具生成相关变量
            lastPowerUpTime = 0;
            lastPowerUpX = 0;
            powerUpsThisMinute = 0;
            lastMinuteCheck = 0;

            lastObstacleX = 0; // 重置上一个障碍物的位置

            // 初始化地面瓷砖，使其铺满屏幕底部并与玩家尺寸匹配
            if (groundTiles != null) {
                for (int x = 0; x < getWidth() + tileWidth; x += tileWidth) {
                    groundTiles.add(new Rect(x, groundLevel, x + tileWidth, groundLevel + tileHeight));
                }
            }

            // 重置滚动速度相关变量，但保持用户设置的速度
            if (difficulty == 0) { // 简单模式
                scrollSpeed = Math.max(5, savedScrollSpeed); // 确保不低于最低速度
            } else { // 困难模式
                scrollSpeed = Math.max(10, savedScrollSpeed); // 确保不低于最低速度
            }
            reverseScrolling = false;

            // 重置死亡动画相关变量
            isDying = false;
            deathStartTime = 0;
            deathVelocityY = -20; // 与跳跃相同的初始速度

            // 重置无敌时间相关变量
            isInvincible = false;
            invincibleStartTime = 0;

            // 释放并重置死亡动画Bitmap
            if (deathAnimationBitmap != null && !deathAnimationBitmap.isRecycled()) {
                deathAnimationBitmap.recycle();
            }
            deathAnimationBitmap = null;

            // 重置其他游戏状态
            paused = false;
            spawnTimer = 0;

            // 不再自动播放游戏音乐，由调用者决定何时播放
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void playMainMenuMusic() {
        if (bgmMain != null) {
            try {
                if (bgmMain.isPlaying()) {
                    bgmMain.stop();
                }
                bgmMain.prepare();
                // 使用设置的音量
                float volume = isBgmMainMuted ? 0.0f : bgmMainVolume;
                bgmMain.setVolume(volume, volume);
                bgmMain.start();
                bgmMain.setLooping(true);
            } catch (IllegalStateException e) {
                // 处理MediaPlayer状态错误
                e.printStackTrace();
                try {
                    bgmMain.release();
                    bgmMain = MediaPlayer.create(getContext(), R.raw.bgm_main);
                    if (bgmMain != null) {
                        // 使用设置的音量
                        float volume = isBgmMainMuted ? 0.0f : bgmMainVolume;
                        bgmMain.setVolume(volume, volume);
                        bgmMain.setLooping(true);
                        bgmMain.start();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void playGameMusic() {
        if (bgmGame != null) {
            try {
                if (bgmGame.isPlaying()) {
                    bgmGame.stop();
                }
                bgmGame.prepare();
                // 使用设置的音量
                float volume = isBgmGameMuted ? 0.0f : bgmGameVolume;
                bgmGame.setVolume(volume, volume);
                bgmGame.start();
                bgmGame.setLooping(true);
            } catch (IllegalStateException e) {
                // 处理MediaPlayer状态错误
                e.printStackTrace();
                try {
                    bgmGame.release();
                    bgmGame = MediaPlayer.create(getContext(), R.raw.bgm_game);
                    if (bgmGame != null) {
                        // 使用设置的音量
                        float volume = isBgmGameMuted ? 0.0f : bgmGameVolume;
                        bgmGame.setVolume(volume, volume);
                        bgmGame.setLooping(true);
                        bgmGame.start();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void update() {
        try {
            switch (gameState) {
                case TRANSITION:
                    // 过渡到游戏状态
                    resetGame();
                    gameState = IN_GAME;
                    // 播放游戏音乐
                    playGameMusic();
                    break;

                case IN_GAME:
                    if (!paused) {
                        // 只有在非死亡状态时才更新分数
                        if (!isDying) {
                            score = (int) ((System.currentTimeMillis() - startTime) / 1000);
                        }

                        // 更新玩家动画
                        animTimer++;
                        if (animTimer % 8 == 0) {
                            animIndex = (animIndex + 1) % 4;
                        }

                        // 更新无敌时间
                        if (isInvincible) {
                            long currentTime = System.currentTimeMillis();
                            if (currentTime - invincibleStartTime >= INVINCIBLE_DURATION) {
                                isInvincible = false;
                            }
                        }

                        // 处理死亡动画
                        if (isDying) {
                            long currentTime = System.currentTimeMillis();
                            if (currentTime - deathStartTime < DEATH_ANIMATION_DURATION) {
                                // 死亡动画进行中
                                deathVelocityY += DEATH_GRAVITY;
                                player.setPosition(player.getBounds().left,
                                        player.getBounds().top + (int) deathVelocityY);
                            } else {
                                // 死亡动画结束，游戏结束
                                gameState = GAME_OVER;
                                if (bgmGame != null && bgmGame.isPlaying()) {
                                    bgmGame.stop();
                                }
                            }
                        } else {
                            // 只有在非死亡状态时才更新地形
                            updateTerrain();

                            // 更新道具
                            if (powerUps != null) {
                                for (int i = 0; i < powerUps.size(); i++) {
                                    PowerUp powerUp = powerUps.get(i);
                                    powerUp.update(scrollSpeed);

                                    // 移除屏幕外的道具
                                    if (powerUp.isOffScreen()) {
                                        powerUps.remove(i);
                                        i--; // 调整索引
                                    }
                                }
                            }

                            // 更新玩家位置
                            if (player != null) {
                                velocityY += gravity;
                                player.setPosition(player.getBounds().left, player.getBounds().top + (int) velocityY);

                                // 地形碰撞检测
                                checkGroundCollision();

                                // 障碍物碰撞检测
                                checkObstacleCollision();

                                // 道具碰撞检测
                                if (powerUps != null) {
                                    for (int i = 0; i < powerUps.size(); i++) {
                                        PowerUp powerUp = powerUps.get(i);
                                        if (player.checkCollision(powerUp.getBounds())) {
                                            // 播放道具音效
                                            soundUtils.playSoundCure();

                                            // 根据道具类型应用效果
                                            if (powerUp.getType() == PowerUp.TYPE_LIFE) {
                                                // 增加生命值
                                                currentLives = Math.min(currentLives + 1, maxLives);
                                            }

                                            // 移除已收集的道具
                                            powerUps.remove(i);
                                            i--; // 调整索引
                                        }
                                    }
                                }

                                // 检查是否掉落屏幕外
                                if (player.getBounds().top > getHeight()) {
                                    gameState = GAME_OVER;
                                    if (bgmGame != null && bgmGame.isPlaying()) {
                                        bgmGame.stop();
                                    }
                                }
                            }
                        }
                    }
                    break;

                case GAME_OVER:
                    // 游戏结束状态不需要更新
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateTerrain() {
        try {
            spawnTimer++;

            // 根据难度调整障碍物生成概率和滚动速度
            int obstacleSpawnChance = 0;
            int spawnThreshold = Math.max(3, 12 - scrollSpeed / 4); // 根据滚动速度动态调整生成阈值

            if (difficulty == 0) { // 简单模式
                // 每10分增加滚动速度
                if (score > 0 && score % 10 == 0) {
                    if (scrollSpeed < maxScrollSpeed) {
                        scrollSpeed = initialScrollSpeed + (score / 10);
                        // 确保滚动速度不超过最大值
                        if (scrollSpeed > maxScrollSpeed) {
                            scrollSpeed = maxScrollSpeed;
                        }
                    }
                }

                // 根据分数和滚动速度调整障碍物生成概率
                // 初始20%概率，每10分增加5%概率，最多50%，同时考虑滚动速度
                obstacleSpawnChance = 20 + (score / 10) * 5 + scrollSpeed / 2;
                if (obstacleSpawnChance > 50 + scrollSpeed / 2) {
                    obstacleSpawnChance = 50 + scrollSpeed / 2;
                }
            } else { // 困难模式
                // 每10分增加滚动速度
                if (score > 0 && score % 10 == 0) {
                    if (scrollSpeed < maxScrollSpeed) {
                        scrollSpeed = initialScrollSpeed + (score / 10);
                        // 确保滚动速度不超过最大值
                        if (scrollSpeed > maxScrollSpeed) {
                            scrollSpeed = maxScrollSpeed;
                        }
                    }
                }

                // 每50分改变滚动方向
                // if (score > 0 && score % 20 == 0) {
                // reverseScrolling = !reverseScrolling;
                // }

                // 根据分数和滚动速度调整障碍物生成概率
                // 初始40%概率，每10分增加10%概率，最多60%，同时考虑滚动速度
                obstacleSpawnChance = 40 + (score / 10) * 10 + scrollSpeed / 2;
                if (obstacleSpawnChance > 60 + scrollSpeed / 2) {
                    obstacleSpawnChance = 60 + scrollSpeed / 2;
                }
            }

            // 生成新的地面瓷砖
            if (spawnTimer >= spawnThreshold) {
                spawnTimer = 0;

                // 计算需要生成的瓷砖数量，确保覆盖高速滚动
                int tilesToGenerate = Math.max(1, scrollSpeed / 5); // 根据速度生成多个瓷砖

                // 计算起始位置
                int startX;
                if (groundTiles != null && !groundTiles.isEmpty()) {
                    Rect lastTile = groundTiles.get(groundTiles.size() - 1);
                    startX = lastTile.right;
                } else if (groundTiles != null) {
                    startX = getWidth();
                } else {
                    startX = getWidth();
                }

                // 连续生成瓷砖，确保无间隙
                for (int i = 0; i < tilesToGenerate; i++) {
                    int newTileX = startX + (i * tileWidth);
                    int groundLevel = getHeight() - 100; // 地面高度
                    groundTiles.add(new Rect(newTileX, groundLevel, newTileX + tileWidth, groundLevel + tileHeight));
                }

                // 生成障碍物 - 基于新生成的瓷砖位置
                if (obstacles != null && groundTiles != null && !groundTiles.isEmpty()) {
                    // 根据分数和速度动态调整障碍物间距，确保每组尖刺之间至少容下3个人物宽度
                    int minSpacing = Math.max(480, tileWidth - scrollSpeed * 2); // 最小间距为3个人物宽度(480px)
                    if (score > 50) {
                        minSpacing = Math.max(480, minSpacing - tileWidth / 4);
                    }
                    if (score > 100) {
                        minSpacing = Math.max(480, minSpacing - tileWidth / 6);
                    }

                    // 为每个新生成的瓷砖生成障碍物
                    for (int i = 0; i < tilesToGenerate; i++) {
                        if (random.nextInt(100) < obstacleSpawnChance) {
                            int tileX = startX + (i * tileWidth);
                            int obstacleX = tileX + tileWidth / 2; // 障碍物放在瓷砖中间位置

                            if (obstacleX > lastObstacleX + minSpacing) {
                                int obstacleY = getHeight() - 100 - 100; // 放在地面瓷砖上方
                                obstacles.add(new Rect(obstacleX, obstacleY, obstacleX + 100, obstacleY + 100));
                                lastObstacleX = obstacleX; // 更新上一个障碍物的位置
                            }
                        }
                    }
                }

                // 生成道具
                if (powerUps != null) {
                    // 检查是否需要重置分钟计数
                    long currentTime = System.currentTimeMillis();
                    long currentMinute = (currentTime - startTime) / 60000; // 转换为分钟
                    long lastMinute = (lastMinuteCheck - startTime) / 60000;

                    if (currentMinute > lastMinute) {
                        powerUpsThisMinute = 0; // 重置分钟计数
                    }
                    lastMinuteCheck = currentTime;

                    // 根据难度调整道具生成概率
                    float powerUpSpawnChance = 0;
                    if (difficulty == 0) { // 简单模式
                        powerUpSpawnChance = LIFE_POWER_UP_SPAWN_PROBABILITY * 100; // 默认30%概率
                    } else { // 困难模式
                        powerUpSpawnChance = LIFE_POWER_UP_SPAWN_PROBABILITY * 50; // 15%概率
                    }

                    // 为每个新生成的瓷砖生成道具
                    for (int i = 0; i < tilesToGenerate; i++) {
                        if (random.nextInt(100) < powerUpSpawnChance) {
                            int tileX = startX + (i * tileWidth);
                            int powerUpX = tileX + tileWidth / 2; // 道具放在瓷砖中间位置
                            int powerUpY = getHeight() - 100 - 150; // 放在地面瓷砖上方150px

                            // 检查是否超过每分钟最大道具数量限制
                            if (powerUpsThisMinute >= 3) {
                                continue; // 超过限制，跳过生成
                            }

                            // 检查道具之间是否有足够的间距
                            int minPowerUpSpacing = 500; // 道具之间的最小间距
                            if (powerUpX > lastPowerUpX + minPowerUpSpacing) {
                                // 检查距离上次生成道具的时间间隔
                                if (currentTime - lastPowerUpTime >= 5000) { // 至少间隔5秒
                                    // 创建生命道具
                                    powerUps.add(new PowerUp(powerUpX, powerUpY, 100, 100, PowerUp.TYPE_LIFE,
                                            lifePowerUpImage, 1.0f, soundUtils.getSoundCure()));
                                    lastPowerUpTime = currentTime;
                                    lastPowerUpX = powerUpX;
                                    powerUpsThisMinute++; // 增加分钟计数
                                }
                            }
                        }
                    }
                }
            }

            // 滚动地形和障碍物
            int currentScrollSpeed = reverseScrolling ? -scrollSpeed : scrollSpeed;

            if (groundTiles != null) {
                for (int i = 0; i < groundTiles.size(); i++) {
                    Rect tile = groundTiles.get(i);
                    tile.offset(-currentScrollSpeed, 0);
                    groundTiles.set(i, tile);
                }

                // 移除屏幕外的地形
                groundTiles.removeIf(tile -> tile.right < 0);
            }

            if (obstacles != null) {
                for (int i = 0; i < obstacles.size(); i++) {
                    Rect obstacle = obstacles.get(i);
                    obstacle.offset(-currentScrollSpeed, 0);
                    obstacles.set(i, obstacle);
                }

                // 移除屏幕外的障碍物
                obstacles.removeIf(obstacle -> obstacle.right < 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkGroundCollision() {
        // 死亡动画期间不进行地面碰撞检测
        if (isDying) {
            return;
        }

        boolean onGround = false;
        Rect playerBounds = player.getBounds();

        // 检查是否站在地面上
        int groundLevel = getHeight() - 100; // 地面高度
        if (playerBounds.bottom >= groundLevel) {
            // 玩家站在屏幕底部
            player.setPosition(player.getBounds().left, groundLevel - 160);
            velocityY = 0;
            isJumping = false;
            doubleJumpAvailable = true; // 着陆后恢复双重跳跃
            onGround = true;
        } else {
            // 检查是否站在地形瓷砖上
            for (Rect tile : groundTiles) {
                // 检查垂直碰撞（落在地形上）
                if (playerBounds.right > tile.left && playerBounds.left < tile.right &&
                        playerBounds.bottom >= tile.top && playerBounds.bottom <= tile.top + 20 &&
                        velocityY >= 0) {
                    player.setPosition(player.getBounds().left, tile.top - 160);
                    velocityY = 0;
                    isJumping = false;
                    doubleJumpAvailable = true; // 着陆后恢复双重跳跃
                    onGround = true;
                    break;
                }
            }
        }

        // 如果没有站在地面上，设置为跳跃状态
        if (!onGround) {
            isJumping = true;
        }
    }

    private void checkObstacleCollision() {
        for (Rect obstacle : obstacles) {
            if (player.checkCollision(obstacle)) {
                // 只有在非无敌状态下才处理碰撞
                if (!isInvincible) {
                    // 碰撞检测到障碍物，扣除生命值
                    currentLives--;

                    // 播放受伤音效
                    soundUtils.playSoundHurt();

                    // 启动无敌时间
                    isInvincible = true;
                    invincibleStartTime = System.currentTimeMillis();

                    // 如果生命值降到0，启动死亡动画
                    if (currentLives <= 0) {
                        isDying = true;
                        deathStartTime = System.currentTimeMillis();
                        deathVelocityY = -20; // 给予向上的初始速度，与跳跃速度一致
                    }

                    // 重置玩家位置
                    int groundLevel = getHeight() - 100; // 地面高度
                    if (player != null) {
                        player.setPosition(playerX, groundLevel - 160);
                        player.setGroundLevel(groundLevel);
                    } else {
                        player = new Player();
                        player.init(playerX, groundLevel - 160, 160, 160, groundLevel);
                    }
                }
                return;
            }
        }
    }

    public void draw(Canvas canvas) {
        try {
            super.draw(canvas);
            if (canvas != null) {
                switch (gameState) {
                    case START_SCREEN:
                        drawStartScreen(canvas);
                        break;
                    case TRANSITION:
                        // 过渡状态可以绘制一些动画效果
                        drawTransition(canvas);
                        break;
                    case IN_GAME:
                        drawGame(canvas);
                        break;
                    case GAME_OVER:
                        drawGameOver(canvas);
                        break;
                    case SETTINGS_SCREEN:
                        drawSettingsScreen(canvas);
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void drawTransition(Canvas canvas) {
        // 简单的过渡效果，可以绘制黑色屏幕
        canvas.drawColor(Color.BLACK);
    }

    private void drawSettingsScreen(Canvas canvas) {
        // 绘制半透明遮罩
        paint.setColor(Color.BLACK);
        paint.setAlpha(180);
        canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
        paint.setAlpha(255);

        // 绘制设置菜单背景（屏幕一半宽度，居中）
        int menuWidth = getWidth() / 2;
        int menuLeft = (getWidth() - menuWidth) / 2;

        // 统一设置选项的高度和间距
        int optionHeight = 120; // 每个设置选项的高度
        int labelContentSpacing = 30; // label与内容的间距
        int optionSpacing = 50; // 选项之间的间距

        // 计算菜单总高度
        int titleHeight = 80; // 标题高度
        int titleSpacing = 100; // 标题与第一个选项的间距

        // 计算所有设置选项的高度
        int totalOptionsHeight = titleHeight;
        totalOptionsHeight += optionHeight + optionSpacing; // 难度选择
        totalOptionsHeight += optionHeight + optionSpacing; // 速度设置
        totalOptionsHeight += optionHeight + optionSpacing; // 主界面BGM音量
        totalOptionsHeight += optionHeight + optionSpacing; // 游戏内BGM音量
        totalOptionsHeight += optionHeight + optionSpacing; // 确认按钮

        int menuHeight = Math.min(titleHeight + titleSpacing + totalOptionsHeight, getHeight() - 100); // 限制高度不超过屏幕高度并保留底部空间
        int menuTop = (getHeight() - menuHeight) / 2;

        paint.setColor(Color.LTGRAY);
        canvas.drawRoundRect(menuLeft, menuTop, menuLeft + menuWidth, menuTop + menuHeight, 20, 20, paint);

        // 绘制标题
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(60);
        String title = "游戏设置";
        float titleWidth = textPaint.measureText(title);
        canvas.drawText(title, (getWidth() - titleWidth) / 2, menuTop + titleHeight - settingsScrollY, textPaint);

        // 初始化设置按钮区域
        int buttonWidth = menuWidth - 80;
        int buttonLeft = menuLeft + 40;
        int currentTop = menuTop + titleHeight + titleSpacing; // 当前绘制位置的顶部

        // 绘制难度选择标题
        textPaint.setTextSize(40);
        String difficultyTitle = "选择难度:";
        canvas.drawText(difficultyTitle, buttonLeft, currentTop - labelContentSpacing - settingsScrollY, textPaint);

        // 绘制难度切换按钮
        int toggleWidth = buttonWidth;
        int toggleHeight = optionHeight;
        int toggleLeft = buttonLeft;
        int toggleTop = currentTop;

        // 绘制背景
        paint.setColor(Color.GRAY);
        canvas.drawRoundRect(toggleLeft, toggleTop - (int) settingsScrollY, toggleLeft + toggleWidth,
                toggleTop + toggleHeight - (int) settingsScrollY, 15, 15, paint);

        // 根据当前难度绘制选中状态
        if (difficulty == 0) { // 简单
            paint.setColor(Color.GREEN);
            canvas.drawRoundRect(toggleLeft, toggleTop - (int) settingsScrollY, toggleLeft + toggleWidth / 2,
                    toggleTop + toggleHeight - (int) settingsScrollY, 15, 15,
                    paint);
        } else { // 困难
            paint.setColor(Color.RED);
            canvas.drawRoundRect(toggleLeft + toggleWidth / 2, toggleTop - (int) settingsScrollY,
                    toggleLeft + toggleWidth,
                    toggleTop + toggleHeight - (int) settingsScrollY, 15, 15, paint);
        }

        // 绘制文字
        textPaint.setColor(Color.WHITE);
        String easyText = "简单";
        String hardText = "困难";
        float easyTextWidth = textPaint.measureText(easyText);
        float hardTextWidth = textPaint.measureText(hardText);
        canvas.drawText(easyText, toggleLeft + (toggleWidth / 2 - easyTextWidth) / 2,
                toggleTop + (toggleHeight + 40) / 2 - settingsScrollY, textPaint);
        canvas.drawText(hardText, toggleLeft + toggleWidth / 2 + (toggleWidth / 2 - hardTextWidth) / 2,
                toggleTop + (toggleHeight + 40) / 2 - settingsScrollY, textPaint);

        // 保存按钮区域用于触摸事件
        if (easyButton == null) {
            easyButton = new GameButton(getContext(),
                    new Rect(toggleLeft, toggleTop - (int) settingsScrollY, toggleLeft + toggleWidth / 2,
                            toggleTop + toggleHeight - (int) settingsScrollY));
        } else {
            easyButton.setBounds(new Rect(toggleLeft, toggleTop - (int) settingsScrollY, toggleLeft + toggleWidth / 2,
                    toggleTop + toggleHeight - (int) settingsScrollY));
        }
        if (hardButton == null) {
            hardButton = new GameButton(getContext(),
                    new Rect(toggleLeft + toggleWidth / 2, toggleTop - (int) settingsScrollY, toggleLeft + toggleWidth,
                            toggleTop + toggleHeight - (int) settingsScrollY));
        } else {
            hardButton.setBounds(
                    new Rect(toggleLeft + toggleWidth / 2, toggleTop - (int) settingsScrollY, toggleLeft + toggleWidth,
                            toggleTop + toggleHeight - (int) settingsScrollY));
        }

        // 更新当前绘制位置
        currentTop += toggleHeight + optionSpacing + titleHeight;

        // 绘制速度设置标题
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(40);
        String speedTitle = "滚动速度:";
        canvas.drawText(speedTitle, buttonLeft, currentTop - labelContentSpacing - settingsScrollY, textPaint);

        // 绘制减号按钮
        int minusButtonLeft = buttonLeft;
        int minusButtonTop = currentTop;
        int buttonSize = 50;
        if (minusButton == null) {
            minusButton = new GameButton(getContext(),
                    new Rect(minusButtonLeft, minusButtonTop - (int) settingsScrollY, minusButtonLeft + buttonSize,
                            minusButtonTop + buttonSize - (int) settingsScrollY));
        } else {
            minusButton.setBounds(
                    new Rect(minusButtonLeft, minusButtonTop - (int) settingsScrollY, minusButtonLeft + buttonSize,
                            minusButtonTop + buttonSize - (int) settingsScrollY));
        }
        minusButton.draw(canvas);
        
        // 绘制加号按钮
        int plusButtonLeft = buttonLeft + buttonWidth - buttonSize;
        int plusButtonTop = currentTop;
        if (plusButton == null) {
            plusButton = new GameButton(getContext(),
                    new Rect(plusButtonLeft, plusButtonTop - (int) settingsScrollY, plusButtonLeft + buttonSize,
                            plusButtonTop + buttonSize - (int) settingsScrollY));
        } else {
            plusButton.setBounds(
                    new Rect(plusButtonLeft, plusButtonTop - (int) settingsScrollY, plusButtonLeft + buttonSize,
                            plusButtonTop + buttonSize - (int) settingsScrollY));
        }
        plusButton.draw(canvas);

        // 绘制进度条
        int progressBarWidth = buttonWidth - buttonSize * 2 - 20; // 减去两个按钮的宽度和间距
        int progressBarHeight = 30;
        int progressBarLeft = buttonLeft + buttonSize + 10; // 在减号按钮右侧
        int progressBarTop = currentTop + 10; // 与按钮对齐

        // 进度条背景
        paint.setColor(Color.DKGRAY);
        canvas.drawRoundRect(progressBarLeft, progressBarTop - (int) settingsScrollY,
                progressBarLeft + progressBarWidth,
                progressBarTop + progressBarHeight - (int) settingsScrollY, 10, 10, paint);

        // 进度条前景
        int maxSpeed = 20; // 简单和困难模式最高速度均为30
        int minSpeed = (difficulty == 0) ? 5 : 10;
        int progressWidth = (int) ((float) (initialScrollSpeed - minSpeed) / (maxSpeed - minSpeed) * progressBarWidth);
        paint.setColor(Color.BLUE);
        canvas.drawRoundRect(progressBarLeft, progressBarTop - (int) settingsScrollY, progressBarLeft + progressWidth,
                progressBarTop + progressBarHeight - (int) settingsScrollY, 10, 10, paint);

        // 绘制速度值
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(30);
        String speedText = initialScrollSpeed + "/" + maxSpeed;
        float speedTextWidth = textPaint.measureText(speedText);
        canvas.drawText(speedText, progressBarLeft + (progressBarWidth - speedTextWidth) / 2,
                progressBarTop + progressBarHeight + 30 - settingsScrollY, textPaint);

        // 更新当前绘制位置
        currentTop += optionHeight + optionSpacing;

        // 绘制主界面BGM音量设置标题
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(40);
        String bgmMainTitle = "主界面音量:";
        canvas.drawText(bgmMainTitle, buttonLeft, currentTop - labelContentSpacing - settingsScrollY, textPaint);

        // 绘制主界面BGM音量减号按钮
        int bgmMainMinusButtonLeft = buttonLeft;
        int bgmMainMinusButtonTop = currentTop;
        if (bgmMainMinusButton == null) {
            bgmMainMinusButton = new GameButton(getContext(),
                    new Rect(bgmMainMinusButtonLeft, bgmMainMinusButtonTop - (int) settingsScrollY,
                            bgmMainMinusButtonLeft + buttonSize,
                            bgmMainMinusButtonTop + buttonSize - (int) settingsScrollY));
        } else {
            bgmMainMinusButton.setBounds(new Rect(bgmMainMinusButtonLeft, bgmMainMinusButtonTop - (int) settingsScrollY,
                    bgmMainMinusButtonLeft + buttonSize,
                    bgmMainMinusButtonTop + buttonSize - (int) settingsScrollY));
        }
        bgmMainMinusButton.draw(canvas);

        // 绘制主界面BGM音量加号按钮
        int bgmMainPlusButtonLeft = buttonLeft + buttonWidth - buttonSize;
        int bgmMainPlusButtonTop = currentTop;
        if (bgmMainPlusButton == null) {
            bgmMainPlusButton = new GameButton(getContext(),
                    new Rect(bgmMainPlusButtonLeft, bgmMainPlusButtonTop - (int) settingsScrollY,
                            bgmMainPlusButtonLeft + buttonSize,
                            bgmMainPlusButtonTop + buttonSize - (int) settingsScrollY));
        } else {
            bgmMainPlusButton.setBounds(new Rect(bgmMainPlusButtonLeft, bgmMainPlusButtonTop - (int) settingsScrollY,
                    bgmMainPlusButtonLeft + buttonSize, bgmMainPlusButtonTop + buttonSize - (int) settingsScrollY));
        }
        bgmMainPlusButton.draw(canvas);

        // 绘制主界面BGM音量静音按钮
        int bgmMainMuteButtonLeft = bgmMainPlusButtonLeft - buttonSize - 10;
        int bgmMainMuteButtonTop = currentTop;
        paint.setColor(isBgmMainMuted ? Color.RED : Color.GRAY);
        canvas.drawRoundRect(bgmMainMuteButtonLeft, bgmMainMuteButtonTop - (int) settingsScrollY,
                bgmMainMuteButtonLeft + buttonSize, bgmMainMuteButtonTop + buttonSize - (int) settingsScrollY, 10,
                10, paint);
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(30);
        canvas.drawText("♪", bgmMainMuteButtonLeft, bgmMainMuteButtonTop + 35 - settingsScrollY, textPaint);
        if (bgmMainMuteButton == null) {
            bgmMainMuteButton = new GameButton(getContext(),
                    new Rect(bgmMainMuteButtonLeft, bgmMainMuteButtonTop - (int) settingsScrollY,
                            bgmMainMuteButtonLeft + buttonSize,
                            bgmMainMuteButtonTop + buttonSize - (int) settingsScrollY));
        } else {
            bgmMainMuteButton.setBounds(new Rect(bgmMainMuteButtonLeft, bgmMainMuteButtonTop - (int) settingsScrollY,
                    bgmMainMuteButtonLeft + buttonSize, bgmMainMuteButtonTop + buttonSize - (int) settingsScrollY));
        }

        // 绘制主界面BGM音量进度条
        int bgmMainProgressBarWidth = buttonWidth - buttonSize * 3 - 30; // 减去三个按钮的宽度和间距
        int bgmMainProgressBarHeight = 30;
        int bgmMainProgressBarLeft = buttonLeft + buttonSize + 10; // 在减号按钮右侧
        int bgmMainProgressBarTop = currentTop + 10; // 与按钮对齐

        // 主界面BGM音量进度条背景
        paint.setColor(Color.DKGRAY);
        canvas.drawRoundRect(bgmMainProgressBarLeft, bgmMainProgressBarTop - (int) settingsScrollY,
                bgmMainProgressBarLeft + bgmMainProgressBarWidth,
                bgmMainProgressBarTop + bgmMainProgressBarHeight - (int) settingsScrollY, 10, 10, paint);

        // 主界面BGM音量进度条前景
        int bgmMainProgressWidth = (int) (bgmMainVolume * bgmMainProgressBarWidth);
        paint.setColor(Color.BLUE);
        canvas.drawRoundRect(bgmMainProgressBarLeft, bgmMainProgressBarTop - (int) settingsScrollY,
                bgmMainProgressBarLeft + bgmMainProgressWidth,
                bgmMainProgressBarTop + bgmMainProgressBarHeight - (int) settingsScrollY, 10, 10, paint);

        // 绘制主界面BGM音量值
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(30);
        String bgmMainVolumeText = Math.round(bgmMainVolume * 100) + "%";
        float bgmMainVolumeTextWidth = textPaint.measureText(bgmMainVolumeText);
        canvas.drawText(bgmMainVolumeText,
                bgmMainProgressBarLeft + (bgmMainProgressBarWidth - bgmMainVolumeTextWidth) / 2,
                bgmMainProgressBarTop + bgmMainProgressBarHeight + 30 - settingsScrollY, textPaint);

        // 更新当前绘制位置
        currentTop += optionHeight + optionSpacing;

        // 绘制游戏内BGM音量设置标题
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(40);
        String bgmGameTitle = "游戏内音量:";
        canvas.drawText(bgmGameTitle, buttonLeft, currentTop - labelContentSpacing - settingsScrollY, textPaint);

        // 绘制游戏内BGM音量减号按钮
        int bgmGameMinusButtonLeft = buttonLeft;
        int bgmGameMinusButtonTop = currentTop;
        if (bgmGameMinusButton == null) {
            bgmGameMinusButton = new GameButton(getContext(),
                    new Rect(bgmGameMinusButtonLeft, bgmGameMinusButtonTop - (int) settingsScrollY,
                            bgmGameMinusButtonLeft + buttonSize,
                            bgmGameMinusButtonTop + buttonSize - (int) settingsScrollY));
        } else {
            bgmGameMinusButton.setBounds(new Rect(bgmGameMinusButtonLeft, bgmGameMinusButtonTop - (int) settingsScrollY,
                    bgmGameMinusButtonLeft + buttonSize,
                    bgmGameMinusButtonTop + buttonSize - (int) settingsScrollY));
        }
        bgmGameMinusButton.draw(canvas);

        // 绘制游戏内BGM音量加号按钮
        int bgmGamePlusButtonLeft = buttonLeft + buttonWidth - buttonSize;
        int bgmGamePlusButtonTop = currentTop;
        if (bgmGamePlusButton == null) {
            bgmGamePlusButton = new GameButton(getContext(),
                    new Rect(bgmGamePlusButtonLeft, bgmGamePlusButtonTop - (int) settingsScrollY,
                            bgmGamePlusButtonLeft + buttonSize,
                            bgmGamePlusButtonTop + buttonSize - (int) settingsScrollY));
        } else {
            bgmGamePlusButton.setBounds(new Rect(bgmGamePlusButtonLeft, bgmGamePlusButtonTop - (int) settingsScrollY,
                    bgmGamePlusButtonLeft + buttonSize, bgmGamePlusButtonTop + buttonSize - (int) settingsScrollY));
        }
        bgmGamePlusButton.draw(canvas);

        // 绘制游戏内BGM音量静音按钮
        int bgmGameMuteButtonLeft = bgmGamePlusButtonLeft - buttonSize - 10;
        int bgmGameMuteButtonTop = currentTop;
        paint.setColor(isBgmGameMuted ? Color.RED : Color.GRAY);
        canvas.drawRoundRect(bgmGameMuteButtonLeft, bgmGameMuteButtonTop - (int) settingsScrollY,
                bgmGameMuteButtonLeft + buttonSize, bgmGameMuteButtonTop + buttonSize - (int) settingsScrollY, 10,
                10, paint);
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(30);
        canvas.drawText("♪", bgmGameMuteButtonLeft, bgmGameMuteButtonTop + 35 - settingsScrollY, textPaint);
        if (bgmGameMuteButton == null) {
            bgmGameMuteButton = new GameButton(getContext(),
                    new Rect(bgmGameMuteButtonLeft, bgmGameMuteButtonTop - (int) settingsScrollY,
                            bgmGameMuteButtonLeft + buttonSize,
                            bgmGameMuteButtonTop + buttonSize - (int) settingsScrollY));
        } else {
            bgmGameMuteButton.setBounds(new Rect(bgmGameMuteButtonLeft, bgmGameMuteButtonTop - (int) settingsScrollY,
                    bgmGameMuteButtonLeft + buttonSize, bgmGameMuteButtonTop + buttonSize - (int) settingsScrollY));
        }

        // 绘制游戏内BGM音量进度条
        int bgmGameProgressBarWidth = buttonWidth - buttonSize * 3 - 30; // 减去三个按钮的宽度和间距
        int bgmGameProgressBarHeight = 30;
        int bgmGameProgressBarLeft = buttonLeft + buttonSize + 10; // 在减号按钮右侧
        int bgmGameProgressBarTop = currentTop + 10; // 与按钮对齐

        // 游戏内BGM音量进度条背景
        paint.setColor(Color.DKGRAY);
        canvas.drawRoundRect(bgmGameProgressBarLeft, bgmGameProgressBarTop - (int) settingsScrollY,
                bgmGameProgressBarLeft + bgmGameProgressBarWidth,
                bgmGameProgressBarTop + bgmGameProgressBarHeight - (int) settingsScrollY, 10, 10, paint);

        // 游戏内BGM音量进度条前景
        int bgmGameProgressWidth = (int) (bgmGameVolume * bgmGameProgressBarWidth);
        paint.setColor(Color.BLUE);
        canvas.drawRoundRect(bgmGameProgressBarLeft, bgmGameProgressBarTop - (int) settingsScrollY,
                bgmGameProgressBarLeft + bgmGameProgressWidth,
                bgmGameProgressBarTop + bgmGameProgressBarHeight - (int) settingsScrollY, 10, 10, paint);

        // 绘制游戏内BGM音量值
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(30);
        String bgmGameVolumeText = Math.round(bgmGameVolume * 100) + "%";
        float bgmGameVolumeTextWidth = textPaint.measureText(bgmGameVolumeText);
        canvas.drawText(bgmGameVolumeText,
                bgmGameProgressBarLeft + (bgmGameProgressBarWidth - bgmGameVolumeTextWidth) / 2,
                bgmGameProgressBarTop + bgmGameProgressBarHeight + 30 - settingsScrollY, textPaint);

        // 更新当前绘制位置
        currentTop += optionHeight + optionSpacing;

        // 绘制确认按钮
        int confirmButtonTop = currentTop;
        if (confirmButton == null) {
            confirmButton = new GameButton(getContext(), new Rect(buttonLeft, confirmButtonTop - (int) settingsScrollY,
                    buttonLeft + buttonWidth, confirmButtonTop + optionHeight - (int) settingsScrollY));
        } else {
            confirmButton.setBounds(new Rect(buttonLeft, confirmButtonTop - (int) settingsScrollY,
                    buttonLeft + buttonWidth, confirmButtonTop + optionHeight - (int) settingsScrollY));
        }
        confirmButton.draw(canvas);

        // 绘制设置界面退出按钮（右上角X）
        if (settingsExitButton == null) {
            settingsExitButton = new GameButton(getContext(),
                    new Rect(menuLeft + menuWidth - 80, menuTop + 20 - (int) settingsScrollY, menuLeft + menuWidth - 20,
                            menuTop + 80 - (int) settingsScrollY));
        } else {
            settingsExitButton.setBounds(
                    new Rect(menuLeft + menuWidth - 80, menuTop + 20 - (int) settingsScrollY, menuLeft + menuWidth - 20,
                            menuTop + 80 - (int) settingsScrollY));
        }
        settingsExitButton.draw(canvas);
    }

    private void drawStartScreen(Canvas canvas) {
        // 初始化玩家位置
        playerX = getWidth() / 5;
        int groundLevel = getHeight() - 100; // 地面高度
        player.setPosition(playerX, groundLevel - 160);

        // 绘制背景图片，铺满整个屏幕
        if (bgImage1 != null) {
            // 创建一个缩放的背景图片以铺满屏幕
            Rect src = new Rect(0, 0, bgImage1.getWidth(), bgImage1.getHeight());
            Rect dst = new Rect(0, 0, getWidth(), getHeight());
            canvas.drawBitmap(bgImage1, src, dst, null);
        } else {
            canvas.drawColor(Color.BLUE);
        }

        // 绘制半透明遮罩
        paint.setColor(Color.BLACK);
        paint.setAlpha(180);
        canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
        paint.setAlpha(255);

        // 绘制标题，居中显示
        textPaint.setTextSize(80);
        textPaint.setColor(Color.WHITE);
        String title = "海绵宝宝跑酷";
        float titleWidth = textPaint.measureText(title);
        canvas.drawText(title, (getWidth() - titleWidth) / 2, 250, textPaint);

        // 调用按钮封装类的绘制方法
        startButton.draw(canvas);
        exitButton.draw(canvas);

        // 绘制海绵宝宝动画
        if (spongeAnim != null && spongeAnim.length > 0) {
            int frameIndex = (int) (System.currentTimeMillis() / 200) % spongeAnim.length;
            // 调整人物模型大小并放置在屏幕右方
            Bitmap currentFrame = spongeAnim[frameIndex];

            // 检查currentFrame是否为null
            if (currentFrame != null) {
                // 创建缩放矩阵，将人物模型缩小到原来的1/2（比之前更大）
                Matrix matrix = new Matrix();
                matrix.postScale(0.5f, 0.5f); // 缩放到原来的1/2

                // 绘制缩放后的人物模型，放置在屏幕左侧偏下位置
                Bitmap scaledBitmap = Bitmap.createBitmap(currentFrame, 0, 0, currentFrame.getWidth(),
                        currentFrame.getHeight(), matrix, true);
                int characterX = getWidth() - getWidth() / 3; // 距离左边100像素
                int characterY = getHeight() - scaledBitmap.getHeight() - 200; // 距离底部200像素
                canvas.drawBitmap(scaledBitmap, characterX, characterY, null);
            }
        }

        // 绘制设置图标按钮
        if (settingsIcon != null) {
            settingsIcon.draw(canvas);

            // 绘制齿轮图标
            paint.setColor(Color.WHITE);
            paint.setStrokeWidth(5);
            int centerX = settingsIcon.getBounds().centerX();
            int centerY = settingsIcon.getBounds().centerY();
            int radius = 20;

            // 绘制外圆
            canvas.drawCircle(centerX, centerY, radius, paint);

            // 绘制齿轮的齿
            for (int i = 0; i < 6; i++) {
                double angle = Math.toRadians(i * 60);
                int x1 = (int) (centerX + (radius - 5) * Math.cos(angle));
                int y1 = (int) (centerY + (radius - 5) * Math.sin(angle));
                int x2 = (int) (centerX + (radius + 10) * Math.cos(angle));
                int y2 = (int) (centerY + (radius + 10) * Math.sin(angle));
                canvas.drawLine(x1, y1, x2, y2, paint);
            }

            // 绘制内圆
            paint.setColor(Color.parseColor("#2196F3"));
            canvas.drawCircle(centerX, centerY, radius / 2, paint);

            // 重新设置画笔颜色为白色以确保其他元素正常绘制
            paint.setColor(Color.WHITE);
        }
    }

    private void drawGame(Canvas canvas) {
        // 绘制背景图片，铺满整个屏幕
        if (bgImage2 != null) {
            // 创建一个缩放的背景图片以铺满屏幕
            Rect src = new Rect(0, 0, bgImage2.getWidth(), bgImage2.getHeight());
            Rect dst = new Rect(0, 0, getWidth(), getHeight());
            canvas.drawBitmap(bgImage2, src, dst, null);
        } else {
            canvas.drawColor(Color.CYAN);
        }

        // 绘制地形
        drawTerrain(canvas);

        // 绘制玩家
        // 如果处于无敌状态，设置玩家半透明效果
        if (isInvincible && !isDying) {
            // 计算透明度，实现忽隐忽现效果
            long currentTime = System.currentTimeMillis();
            long elapsed = currentTime - invincibleStartTime;
            // 使用正弦函数创建闪烁效果，频率更高一些
            float sinValue = (float) Math.abs(Math.sin(elapsed / 50.0));
            // 将sin值从[0,1]映射到[0.4,1.0]的透明度范围
            int alpha = (int) (0.4 + 0.6 * sinValue) * 255;

            // 保存当前画笔alpha值
            int originalAlpha = paint.getAlpha();

            // 设置新的透明度
            paint.setAlpha(alpha);

            // 绘制玩家
            player.draw(canvas, spongeAnim, isDying, (int) velocityY, animIndex);

            // 恢复原始画笔alpha值
            paint.setAlpha(originalAlpha);
        } else {
            // 正常绘制玩家
            player.draw(canvas, spongeAnim, isDying, (int) velocityY, animIndex);
        }

        // 绘制道具
        if (powerUps != null) {
            for (PowerUp powerUp : powerUps) {
                powerUp.draw(canvas);
            }
        }

        // 绘制分数
        textPaint.setTextSize(60); // 增大得分显示大小
        textPaint.setColor(Color.BLACK);
        canvas.drawText("得分: " + score, 100, 100, textPaint);

        // 绘制生命值
        int lifeIconSize = 50; // 生命图标大小
        int lifeIconSpacing = 10; // 生命图标间距
        int lifeStartX = 100; // 生命值显示起始X坐标
        int lifeY = 150; // 生命值显示Y坐标

        for (int i = 0; i < maxLives; i++) {
            Bitmap lifeBitmap = (i < currentLives) ? lifeImage : notLifeImage;
            if (lifeBitmap != null) {
                // 缩放生命图标
                Matrix matrix = new Matrix();
                float scale = (float) lifeIconSize / Math.max(lifeBitmap.getWidth(), lifeBitmap.getHeight());
                matrix.postScale(scale, scale);
                Bitmap scaledLifeBitmap = Bitmap.createBitmap(lifeBitmap, 0, 0, lifeBitmap.getWidth(),
                        lifeBitmap.getHeight(), matrix, true);

                // 绘制生命图标
                canvas.drawBitmap(scaledLifeBitmap, lifeStartX + i * (lifeIconSize + lifeIconSpacing), lifeY, null);
            }
        }

        // 绘制无敌时间进度条
        if (isInvincible && !isDying) { // 生命值归0死亡时不显示无敌时间条
            long currentTime = System.currentTimeMillis();
            long elapsed = currentTime - invincibleStartTime;
            float progress = Math.max(0, 1.0f - (float) elapsed / INVINCIBLE_DURATION);

            // 进度条位置在玩家头顶
            int barWidth = 150; // 增大进度条宽度
            int barHeight = 20; // 增大进度条高度
            int barX = player.getBounds().left + (player.getBounds().width() - barWidth) / 2;
            int barY = player.getBounds().top - 30;

            // 绘制背景
            paint.setColor(Color.GRAY);
            canvas.drawRect(barX, barY, barX + barWidth, barY + barHeight, paint);

            // 绘制进度（改为白色）
            paint.setColor(Color.WHITE);
            canvas.drawRect(barX, barY, barX + (int) (barWidth * progress), barY + barHeight, paint);

            // 绘制"无敌中"文字
            textPaint.setColor(Color.WHITE);
            textPaint.setTextSize(30);
            String invincibleText = "无敌中";
            float textWidth = textPaint.measureText(invincibleText);
            canvas.drawText(invincibleText, barX + (barWidth - textWidth) / 2, barY - 10, textPaint);

            // 恢复textPaint颜色
            textPaint.setColor(Color.BLACK);
        }

        // 绘制滚动速度
        textPaint.setTextSize(60);
        textPaint.setColor(Color.BLACK);
        String speedText = "速度: " + scrollSpeed;
        float speedTextWidth = textPaint.measureText(speedText);
        // 在屏幕中央上方显示速度，与得分在同一水平线上
        canvas.drawText(speedText, (getWidth() - speedTextWidth) / 2, 100, textPaint);

        settingsButton.draw(canvas);

        // 绘制白色暂停图标（两个竖条）
        paint.setColor(Color.WHITE);
        int barWidth = 8;
        int barHeight = 30;
        int barSpacing = 10;
        int barsCenterX = settingsButton.getBounds().left + settingsButton.getBounds().width() / 2;
        int barsCenterY = settingsButton.getBounds().top + settingsButton.getBounds().height() / 2;

        // 绘制左侧竖条
        canvas.drawRect(barsCenterX - barSpacing / 2 - barWidth, barsCenterY - barHeight / 2,
                barsCenterX - barSpacing / 2, barsCenterY + barHeight / 2, paint);

        // 绘制右侧竖条
        canvas.drawRect(barsCenterX + barSpacing / 2, barsCenterY - barHeight / 2,
                barsCenterX + barSpacing / 2 + barWidth, barsCenterY + barHeight / 2, paint);

        // 绘制暂停菜单
        if (paused) {
            // 绘制半透明遮罩
            paint.setColor(Color.BLACK);
            paint.setAlpha(180);
            canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
            paint.setAlpha(255);

            // 绘制暂停菜单
            paint.setColor(Color.LTGRAY);
            canvas.drawRoundRect(getWidth() / 2 - 300, getHeight() / 2 - 250, getWidth() / 2 + 300,
                    getHeight() / 2 + 300, 20, 20, paint);

            // 调整按钮位置和顺序：继续、返回主界面、退出
            int buttonWidth = 400;
            int buttonHeight = 100;
            int buttonSpacing = 30;

            // 只在按钮为null时创建新对象，否则只更新位置
            if (continueButton == null) {
                // continueButton = new GameButton(getContext(), continueButtonBounds);
                continueButton = new GameButton(getContext(),
                        new Rect(
                                (getWidth() - buttonWidth) / 2,
                                getHeight() / 2 - buttonHeight - buttonSpacing / 2 + 20,
                                (getWidth() + buttonWidth) / 2,
                                getHeight() / 2 - buttonSpacing / 2 + 20),
                        "继续游戏",
                        -11751600, -8206459,
                        0xFFFFFFFF, 18, 20);
            }

            if (pauseMainButton == null) {
                pauseMainButton = new GameButton(getContext(),
                        new Rect(
                                (getWidth() - buttonWidth) / 2,
                                getHeight() / 2,
                                (getWidth() + buttonWidth) / 2,
                                getHeight() / 2 + buttonHeight),
                        "返回主界面",
                        -26624, -21197,
                        0xFFFFFFFF, 18, 20);
            }

            if (pauseExitButton == null) {
                pauseExitButton = new GameButton(getContext(),
                        new Rect(
                                (getWidth() - buttonWidth) / 2,
                                getHeight() / 2 + buttonHeight + buttonSpacing,
                                (getWidth() + buttonWidth) / 2,
                                getHeight() / 2 + buttonHeight * 2 + buttonSpacing),
                        "退出游戏",
                        -769226, -628386,
                        0xFFFFFFFF, 18, 20);
            }
            continueButton.draw(canvas);
            pauseMainButton.draw(canvas);
            pauseExitButton.draw(canvas);

            // 绘制文字
            textPaint.setColor(Color.BLACK);
            textPaint.setTextSize(50);
            String pauseText = "游戏暂停";
            float pauseTextWidth = textPaint.measureText(pauseText);
            canvas.drawText(pauseText, (getWidth() - pauseTextWidth) / 2, getHeight() / 2 - 180, textPaint);
        }
    }

    private void drawTerrain(Canvas canvas) {
        // 绘制地面瓷砖，使其自适应屏幕大小
        paint.setColor(Color.GREEN);
        for (Rect tile : groundTiles) {
            if (groundImage != null) {
                // 缩放地面图片以适应瓷砖大小
                Rect src = new Rect(0, 0, groundImage.getWidth(), groundImage.getHeight());
                canvas.drawBitmap(groundImage, src, tile, null);
            } else {
                canvas.drawRect(tile, paint);
            }
        }

        // 绘制障碍物，使其自适应屏幕大小
        paint.setColor(Color.RED);
        for (Rect obstacle : obstacles) {
            if (obstacleImage != null) {
                // 缩放障碍物图片以适应障碍物大小
                Rect src = new Rect(0, 0, obstacleImage.getWidth(), obstacleImage.getHeight());
                canvas.drawBitmap(obstacleImage, src, obstacle, null);
            } else {
                canvas.drawRect(obstacle, paint);
            }
        }
    }

    private void drawGameOver(Canvas canvas) {
        // 死亡界面不显示人物模型
        // 绘制半透明覆盖层
        paint.setColor(Color.BLACK);
        paint.setAlpha(180);
        canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
        paint.setAlpha(255);

        // 绘制重新开始、返回主界面、退出按钮（与首页样式统一，调整顺序和间距）
        int buttonWidth = 400;
        int buttonHeight = 100;
        int buttonSpacing = 30; // 调整间距

        // 定义按钮位置，按顺序：重新开始、返回主界面、退出
        if (restartButton == null) {
            restartButton = new GameButton(getContext(),
                    new Rect(
                            (getWidth() - buttonWidth) / 2,
                            getHeight() / 2 - buttonHeight - buttonSpacing,
                            (getWidth() + buttonWidth) / 2,
                            getHeight() / 2 - buttonSpacing),
                    "重新开始",
                    0xFFFFC107, 0xFFFFA000,
                    0xFFFFFFFF, 18, 20);
        }

        if (dieMainButton == null) {
            dieMainButton = new GameButton(getContext(),
                    new Rect(
                            (getWidth() - buttonWidth) / 2,
                            getHeight() / 2,
                            (getWidth() + buttonWidth) / 2,
                            getHeight() / 2 + buttonHeight),
                    "主菜单",
                    0xFF2196F3, 0xFF1976D2,
                    0xFFFFFFFF, 18, 20);
        }

        if (dieExitButton == null) {
            dieExitButton = new GameButton(getContext(),
                    new Rect(
                            (getWidth() - buttonWidth) / 2,
                            getHeight() / 2 + buttonHeight + buttonSpacing,
                            (getWidth() + buttonWidth) / 2,
                            getHeight() / 2 + buttonHeight * 2 + buttonSpacing),
                    "退出游戏",
                    0xFFF44336, 0xFFD32F2F,
                    0xFFFFFFFF, 18, 20);
        }

        // 调用按钮封装类的绘制方法
        restartButton.draw(canvas);
        dieMainButton.draw(canvas);
        dieExitButton.draw(canvas);

        // 绘制游戏结束文本
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(80);
        canvas.drawText("游戏结束", getWidth() / 2 - 150, 300, textPaint);

        // 绘制最终分数
        textPaint.setTextSize(60);
        canvas.drawText("最终得分: " + score, getWidth() / 2 - 150, 400, textPaint);
    }

    public void pause() {
        if (gameThread != null) {
            gameThread.setRunning(false);
        }
    }

    public void resume() {
        if (gameThread != null) {
            gameThread.setRunning(true);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 屏幕尺寸变化时重新初始化按钮位置
        initButtons();
    }

    // 游戏线程类
    private class GameThread extends Thread {
        private SurfaceHolder surfaceHolder;
        private boolean running;
        private long targetFPS = 60;
        private long targetTime = 1000 / targetFPS;

        public GameThread(SurfaceHolder surfaceHolder) {
            this.surfaceHolder = surfaceHolder;
        }

        public void setRunning(boolean running) {
            this.running = running;
        }

        @Override
        public void run() {
            long lastTime = System.nanoTime();
            double amountOfTicks = 60.0;
            double ns = 1000000000 / amountOfTicks;
            double delta = 0;
            long timer = System.currentTimeMillis();
            int frames = 0;

            while (running) {
                long now = System.nanoTime();
                delta += (now - lastTime) / ns;
                lastTime = now;

                while (delta >= 1) {
                    update();
                    delta--;
                }

                Canvas canvas = null;
                try {
                    canvas = surfaceHolder.lockCanvas();
                    if (canvas != null) {
                        synchronized (surfaceHolder) {
                            draw(canvas);
                        }
                        frames++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (canvas != null) {
                        try {
                            surfaceHolder.unlockCanvasAndPost(canvas);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                if (System.currentTimeMillis() - timer > 1000) {
                    timer += 1000;
                    frames = 0;
                }

                // 确保每帧至少休眠1ms，避免CPU过高
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}